<%--
  Created by IntelliJ IDEA.
  User: JonnyJiang
  Date: 2021/6/5
  Time: 20:45
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html lang="en-US">
<head>
    <title>管理系统</title>
    <link rel="stylesheet" href="${pageContext.request.contextPath}/static/bootstrap-3.3.7-dist/css/bootstrap.min.css">
    <style type="text/css">
        #inputDep, #updateDep {
            width: 15%;
        }

        body{
            background: url("${pageContext.request.contextPath}/static/imgs/index.jpg") no-repeat;
            background-size: cover;
        }
    </style>
</head>
<body>
<div class="container">
    <div class="row">
        <div class="col-md-4"><h1>管理系统</h1></div>
    </div>
    <div class="row">
        <div class="col-md-4 col-md-offset-8">
            <button id="add" class="btn-primary btn-sm" data-toggle="modal" data-target="#myModal">新增</button>
            <button class="btn-danger btn-sm" id="delMore">删除</button>
        </div>
    </div>
    <div class="row">
        <table class="table table-hover" id="emp_table">
            <thead>
            <tr>
                <th><input type="checkbox" class="checkAll"></th>
                <th>#</th>
                <th>姓名</th>
                <th>性别</th>
                <th>电话</th>
                <th>部门</th>
                <th>操作</th>
            </tr>
            </thead>

            <tbody>

            </tbody>

        </table>
    </div>
    <div class="row" id="footer">
    </div>

<%--    添加模态框--%>
    <div class="modal fade" tabindex="-1" role="dialog" id="myModal">
        <div class="modal-dialog" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span
                            aria-hidden="true">&times;</span></button>
                    <h4 class="modal-title">员工信息增加</h4>
                </div>
                <div class="modal-body">

                    <%--                    action="${pageContext.request.contextPath}/addEmp"--%>
                    <form class="form-horizontal" method="post" id="addForm">
                        <div class="form-group">
                            <label for="inputName" class="col-sm-2 control-label">姓名</label>
                            <div class="col-sm-4" style="padding-left: 0;">
                                <input type="text" class="form-control" id="inputName" name="empName" placeholder="姓名">
                                <span class="help-block"></span>
                                <%--                                pattern="^[a-zA-Z][a-zA-Z0-9_]{4,15}$" oninvalid="setCustomValidity('不能以数字开头、不能为空且长度为6~20位！')"--%>
                            </div>
                        </div>
                        <div class="form-group">
                            <label for="inputGender" class="col-sm-2 control-label">性别</label>
                            <div id="inputGender">
                                <label class="radio-inline">
                                    <input type="radio" name="empGender" value="男" checked> 男
                                </label>
                                <label class="radio-inline">
                                    <input type="radio" name="empGender" value="女"> 女
                                </label>
                            </div>

                        </div>

                        <div class="form-group">
                            <label for="inputPhone" class="col-sm-2 control-label">电话</label>
                            <div class="col-sm-4" style="padding-left: 0;">
                                <input type="text" class="form-control" id="inputPhone" name="empPhone"
                                       placeholder="电话">
                                <span class="help-block"></span>
                                <%--                                pattern="^(13[0-9]|14[5|7]|15[0|1|2|3|4|5|6|7|8|9]|18[0|1|2|3|5|6|7|8|9])\d{8}$" oninvalid="setCustomValidity('请输入正确格式的电话号码！')"--%>
                            </div>
                        </div>
                        <div class="form-group">
                            <label for="inputDep" class="col-sm-2 control-label">部门</label>

                            <select class="form-control" id="inputDep" name="depId">

                            </select>
                        </div>
                        <div class="modal-footer">
                            <button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>
                            <button type="button" class="btn btn-primary" onclick="save()">保存</button>
                        </div>
                    </form>
                </div>

            </div><!-- /.modal-content -->
        </div><!-- /.modal-dialog -->
    </div><!-- /.modal -->


<%--    更新模态款--%>

    <div class="modal fade" tabindex="-1" role="dialog" id="myModalUpdate">
        <div class="modal-dialog" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span
                            aria-hidden="true">&times;</span></button>
                    <h4 class="modal-title">员工信息编辑</h4>
                </div>
                <div class="modal-body">

                    <%--                    action="${pageContext.request.contextPath}/addEmp"--%>
                    <form class="form-horizontal" method="post" id="updateForm">
                        <div class="form-group">
                            <label for="updateName" class="col-sm-2 control-label">姓名</label>
                            <div class="col-sm-4" style="padding-left: 0;">
                                <p class="form-control-static" id="updateName"></p>
                            </div>
                        </div>
                        <div class="form-group">
                            <label for="updateGender" class="col-sm-2 control-label">性别</label>
                            <div id="updateGender">
                                <label class="radio-inline">
                                    <input type="radio" name="empGender" value="男" checked> 男
                                </label>
                                <label class="radio-inline">
                                    <input type="radio" name="empGender" value="女"> 女
                                </label>
                            </div>

                        </div>

                        <div class="form-group">
                            <label for="updatePhone" class="col-sm-2 control-label">电话</label>
                            <div class="col-sm-4" style="padding-left: 0;">
                                <input type="text" class="form-control" id="updatePhone" name="empPhone"
                                       placeholder="电话">
                                <span class="help-block"></span>
                            </div>
                        </div>
                        <div class="form-group">
                            <label for="updateDep" class="col-sm-2 control-label">部门</label>

                            <select class="form-control" id="updateDep" name="depId">

                            </select>

                        </div>
                        <div class="modal-footer">
                            <button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>
                            <button type="button" class="btn btn-primary" onclick="update()">更新</button>
                        </div>
                    </form>
                </div>

            </div><!-- /.modal-content -->
        </div><!-- /.modal-dialog -->
    </div><!-- /.modal -->

<%--    单个删除模态框--%>
    <div class="modal fade" tabindex="-1" role="dialog" id="myModalDel">
        <div class="modal-dialog" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span
                            aria-hidden="true">&times;</span></button>
                    <h4 class="modal-title">员工信息删除</h4>
                </div>
                <div class="modal-body">
                    <p>确认删除这条（些）记录吗？</p>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>
                    <button type="button" class="btn btn-danger" onclick="deleteEmp()">删除</button>
                </div>
            </div><!-- /.modal-content -->
        </div><!-- /.modal-dialog -->
    </div><!-- /.modal -->

<%--    提示信息--%>
    <div class="modal fade" tabindex="-1" role="dialog" id="tip">
        <div class="modal-dialog" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span
                            aria-hidden="true">&times;</span></button>
                    <h4 class="modal-title">提示信息</h4>
                </div>
                <div class="modal-body">
                    <p id="tipContent"></p>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-success" data-dismiss="modal">关闭</button>
                </div>
            </div><!-- /.modal-content -->
        </div><!-- /.modal-dialog -->
    </div><!-- /.modal -->

</div>

<script src="${pageContext.request.contextPath}/static/js/jquery.min.js"></script>
<script src="${pageContext.request.contextPath}/static/bootstrap-3.3.7-dist/js/bootstrap.min.js"></script>

<script type="text/javascript">

    var totalPage,currentPage;

    var nameVld = /(^[a-zA-Z][a-zA-Z0-9_]{4,15}$)|(^[\u4e00-\u9fa5]{2,}[a-zA-Z0-9_]{0,10}$)/;
    var nameMsg = "用户名不能以数字开头、不能为空且长度为6~20位或者2~6位中文！";
    var phoneVld = /^(13[0-9]|14[5|7]|15[0-9]|18[0-9])\d{8}$/;
    var phoneMsg = "请输入正确格式的电话号码！";

    $(function () {
        // show(1);
        show(1);
    });

    function show(pn) {
        $.ajax({
            url: "${pageContext.request.contextPath}/empAll",
            data: "pn=" + pn,
            method: "GET",
            success: function (result) {
                build_table(result);
                build_pageInfo(result);

                // build_nav(result);
            }
        });
    }

    function showDep(elem) {
        $.ajax({
            url: "${pageContext.request.contextPath}/dep",
            method: "GET",
            success: function (result) {
                build_dep(result, elem);
            }
        });
    }

    function build_dep(result, elem) {
        elem.empty();
        var select = elem;
        select.empty();
        var deps = result.data.dep;
        $.each(deps, function (index, tmp) {
            var option = $("<option></option>").attr("value", index + 1).append(tmp.depName);
            select.append(option);
        });

    }

    function build_table(result) {
        $("#emp_table tbody").empty();
        var emps = result.data.data.list;
        $.each(emps, function (index, item) {
            var checkOne = $("<td><input type='checkbox' class='checkItem'></td>");
            var empId = $("<td></td>").append(item.empId);
            var empName = $("<td></td>").append(item.empName);
            var empGender = $("<td></td>").append(item.empGender);
            var empPhone = $("<td></td>").append(item.empPhone);
            var empDepName = $("<td></td>").append(item.department.depName);
            var editBtn = $("<button></button>").addClass("btn-primary btn-xs editBtn").append($("<span></span>")
                .addClass("glyphicon glyphicon-pencil")).append("编辑").attr("empId",item.empId);
            var delBtn = $("<button></button>").addClass("btn-danger btn-xs delBtn").append($("<span></span>")
                .addClass("glyphicon glyphicon-trash")).append("删除").attr("empId",item.empId);;
            var btn = $("<td></td>").append(editBtn).append(" ").append(delBtn);

            var row = $("<tr></tr>");
            row.append(checkOne);
            row.append(empId).append(empName).append(empGender).append(empPhone).append(empDepName).append(btn);
            row.appendTo("#emp_table tbody");
        });
    }

    function build_pageInfo(result) {
        $("#footer").empty();
        var pI = result.data.data;
        totalPage = pI.total;
        currentPage = pI.pageNum;
        var pi = $("<div></div>").addClass("row col-md-4").append("当前 " + pI.pageNum + "页 总" + pI.pages + "页 总" + pI.total + "记录");
        pi.appendTo("#footer");

        //################################################################

        var nab = $("<div></div>").addClass("row col-md-4 col-md-offset-8");
        var nav = $("<nav></nav>");
        var ul = $("<ul></ul>").addClass("pagination pagination-sm");
        var fir = $("<li></li>").append($("<a></a>").attr("href", "#").append($("<span></span>").append("首页")));
        fir.click(function () {
            show(1);
        });
        var pre = $("<li></li>").append($("<a></a>").attr("href", "#")
            .append($("<span></span>").append("&laquo;")));
        if (!result.data.data.hasPreviousPage) {
            pre.addClass("disabled");
        }
        pre.click(function () {
            show(result.data.data.pageNum - 1);
        });
        ul.append(fir).append(pre);

        $.each(result.data.data.navigatepageNums, function (index, tmp) {
            const t = $("<li></li>").append($("<a></a>").attr("href", "#").append(tmp));
            if (tmp === result.data.data.pageNum) {
                t.addClass("active");
            }
            t.click(function () {
                show(tmp);
            });
            ul.append(t);
        });
        let next = $("<li></li>").append($("<a></a>").attr("href", "#")
            .append($("<span></span>").append("&raquo;")));
        if (!result.data.data.hasNextPage) {
            next.addClass("disabled");
        }
        next.click(function () {
            show(result.data.data.pageNum + 1);
        });
        ul.append(next);
        let lst = $("<li></li>").append($("<a></a>").attr("href", "#").append($("<span></span>").append("末页")));
        lst.click(function () {
            show(result.data.data.pages);
        });
        ul.append(lst);
        nav.append(ul);
        nab.append(nav);
        nab.appendTo("#footer");
    }

    function showValidMsg(elem, invalid, msg) {
        elem.parent().removeClass("has-success has-error");
        elem.next().text("");
        if (invalid) {
            elem.parent().addClass("has-success");
        } else {
            elem.parent().addClass("has-error");
        }
        elem.next().text(msg);
    }

    function  validInput(){
        // $("#myModal").modal("show");

        if(inputValid($("#inputName"),nameVld)){
            if($("#addForm").attr("nameInvalid") === "true"){
                showValidMsg($("#inputName"), true,"");
            }else{
                showValidMsg($("#inputName"), false,"用户已存在");
            }
        }else{
            showValidMsg($("#inputName"),false,nameMsg);
            return false;
        }
        if (inputValid($("#inputPhone"),phoneVld)){
            showValidMsg($("#inputPhone"),true,"");
            return true;
        }else{
            showValidMsg($("#inputPhone"),false,phoneMsg);
            return false;
        }
    }

    $("#inputName").change(function () {
        let content = this.value;
        $.ajax({
            url: "${pageContext.request.contextPath}/checkUser",
            dataType: "json",
            data: "empName="+content,
            type: "POST",
            success: function (result){
                let nameInvalid = false;
                if(result.status === 100){
                    showValidMsg($("#inputName"),false,result.data.msg);
                }else{
                    showValidMsg($("#inputName"),true,"");
                    nameInvalid = true;
                }
                $("#addForm").attr("nameInvalid",nameInvalid);
            }
        });
    });


    function inputValid(elem,pat){
        return pat.test(elem.val());
    }
    function save() {
        if(!validInput()){
            return false;
        }

        if($("#addForm").attr("nameInvalid") === "false"){
            return false;
        }

        $.ajax({
            url: "${pageContext.request.contextPath}/emp",
            type: "POST",
            dataType: 'json',
            data: $("#addForm").serializeArray(),
            success: function (result) {
                if (result.status === 200) {
                    $("#myModal").modal("hide");
                    $("#tipContent").text("添加成功！！！");
                    $("#tip").modal("show");
                    show(totalPage);
                }else{
                }

            },
            error: function () {
                // save();
            }
        });
    }

    // 点击编辑按钮动态获取该人员的信息
    function showEmpInfo(elem){
        const empId = elem.attr("empId");
        $.ajax({
            url:"${pageContext.request.contextPath}/emp",
            type: "GET",
            dataType: "json",
            data: "empId="+empId,
            success: function (result){
                if(result.status == 200) {
                   let emp = result.data.emp;
                   $("#updateForm").attr("empId",emp.empId);
                   $("#updateName").text(emp.empName);
                   $("#updateGender").val([emp.empGender]);
                   $("#updatePhone").val(emp.empPhone);
                   $("#updateDep").val([emp.depId]);

                }
            }
        });
    }

    //更新信息
    function update(){
        if(!inputValid($("#updatePhone"),phoneVld)){
            return false;

        }

        //todo 获取id name
        const d = $("#updateForm").serializeArray();
        d.push({name:"empName",value:$("#updateName").text()},{name:"empId",value:$("#updateForm").attr("empId")});
        $.ajax({
            url: "${pageContext.request.contextPath}/emp",
            type: "PUT",
            dataType: 'json',
            data: d,
            success: function (result) {
                if (result.status === 200) {
                    $("#myModalUpdate").modal("hide");
                    $("#tipContent").text("修改成功！！！");
                    $("#tip").modal("show");
                    show(currentPage);
                }else{
                }

            },
            error: function () {
                // save();
            }
        });

    }

    function deleteEmp(){
        let delForm = $("#myModalDel");
        let deleData = null;

        if ($("#delMore").attr("delIdItems") === ""){
            deleData = delForm.attr("empId");
        }else{
            deleData = $("#delMore").attr("delIdItems");
        }

        console.log(deleData);
        $.ajax({
            url: "${pageContext.request.contextPath}/emp/" + deleData,
            // +"/"+"empId="+delForm.attr("empId")
            type: "DELETE",
            success: function (result){
                if (result.status === 200){
                    $("#myModalDel").modal("hide");
                    $("#tipContent").text("删除成功！！！！");
                    $("#tip").modal("show");
                    $(".checkAll").prop("checked",false);
                    show(currentPage);
                }else{

                }
            }
        });
    }
    $(document).on("click", ".editBtn", function (){
        showDep($("#updateDep"));
        showEmpInfo($(this));
        $("#myModalUpdate").modal("show");
    });


    // 删除单个记录
    $(document).on("click",".delBtn",function (){
        let empId = $(this).attr("empId");
        $("#myModalDel").modal("show").attr("empId",empId);
    })

    // 清空数据
    $("#add").click(function () {
        $("#addForm")[0].reset();
        $("#addForm").find(".help-block").html("")
        $("#addForm").find("*").removeClass("has-error has-success");
        $("#addForm").attr("nameInvalid", false);
        showDep($("#inputDep"));
    });

    // attr=>自定义属性
    // prop=>原生属性
    // 定义全选、全不选
    $(".checkAll").click(function (){
        $(".checkItem").prop("checked",$(this).prop("checked"));
    });

    // 当所有单选都被选中等价于全选
    $(document).on("click",".checkItem",function (){
       let isCheckAll = $(".checkItem:checked").length == $(".checkItem").length;
       $(".checkAll").prop("checked",isCheckAll);
    });

    $("#delMore").click(function (){
        $("#delMore").attr("delIdItems","");
        let delIdItems = "";
        $.each($(".checkItem:checked"),function (){
           delIdItems += $(this).parents("tr").find("td:eq(1)").text()+"-";
        });
        delIdItems = delIdItems.substring(0, delIdItems.length - 1);
        $("#delMore").attr("delIdItems",delIdItems);
        $("#myModalDel").modal("show");
    });
</script>
</body>
</html>
